package com.spsyry.pay.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.spsyry.api.OrderApi;
import com.spsyry.api.vo.NotifyPay2OrderVo;
import com.spsyry.pay.domain.PaymentOrder;
import com.spsyry.pay.enums.PayOrderEnum;
import com.spsyry.pay.mapper.PaymentOrderMapper;
import com.spsyry.pay.vo.mq.MqOrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.spsyry.pay.constatant.RabbitmqConstant;
import java.util.List;


//@Component
//@RabbitListener(queues = RabbitmqConstant.MQ_QUEUE_NAME)
@Slf4j
public class RabbitmqListener {
    @Autowired
    private OrderApi orderApi;
    @Autowired
    private PaymentOrderMapper paymentOrderMapper;

    @RabbitHandler
    public void handler(String str, Message message, Channel channel) {
        //str保存日志,message消息
        log.info("str接收到的信息:str{}",str);
        MqOrderVo mqOrderVo = JSON.parseObject(str, MqOrderVo.class);

        List<PaymentOrder> list = this.paymentOrderMapper.selectPaymentOrderList(PaymentOrder.builder().merchantOrderNo(mqOrderVo.getOrderId()).build());
        //状态判断
        if(list!=null&&list.size()>=1){
            PaymentOrder paymentOrder = list.get(0);
            //判断这个订单是不是已支付状态
            if (paymentOrder.getOrderStatus().intValue()!= PayOrderEnum.SUCCESS.getDescription()){
                //通过订单号修改状态的。
                //把微信的原始值保留到库
                int updateCount = this.paymentOrderMapper.updatePaymentOrderId(PaymentOrder.builder().merchantOrderNo(mqOrderVo.getOrderId()).orderStatus(PayOrderEnum.REFUND.getDescription()).build());

                NotifyPay2OrderVo addCreateVo = new NotifyPay2OrderVo();
                addCreateVo.setOrderId(mqOrderVo.getOrderId());
                addCreateVo.setStatus(mqOrderVo.getStatus());
                this.orderApi.createOrder(addCreateVo);
            }
        }
    }
}
